package com.msmall.community.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;

import com.msmall.base.util.Constants;
import com.msmall.base.util.FileIO;
import com.msmall.base.util.WatermarkerUtil;

public class SightUtil {
	public static final String PREFIX_WML = "file/wml/sight/";
	public static final String PREFIX_HTML = "file/html/sight/";
	public static final String HOME_PATH = "/home/";
	
	/**
	 * [0] 路径 id/home/
	 * [1]名称 huangshan.jpg
	 * @param file
	 * @param sightid
	 * @param uat
	 * @return
	 */
	public static String[] saveImage(File file, String filename, Long sightid, String uat){
		String path = sightid + HOME_PATH;
		String ext = filename.substring(filename.indexOf("."));
		String newfilename = getFileName() + ext;
		File target = new File(getAbsoluteHomePath(sightid, uat)+newfilename);
		if (target.exists()) {
			target.delete();
		}else{
			File tFolder = new File(getAbsoluteHomePath(sightid, uat));
			if(!tFolder.exists()){
				tFolder.mkdirs();
			}
		}
		try {
			IOUtils.copyLarge(new FileInputStream(file), new FileOutputStream(target));
			WatermarkerUtil.markText(target, ext, null, 0, 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new String[]{path, newfilename};
	}
	
	public static String getAbsoluteHomePath(Long sightid, String uat){
		return Constants.ROOTPATH + getHomePath(sightid, uat);
	}
	
	public static String getFileName(){
		return FileIO.getRandomFileName();
	}
	/**
	 * 生成图片路径 file/html/sight/id/home/
	 * @return
	 */
	public static String getHomePath(Long sightid, String uat){
		String path = "";
		if(uat.equals(Constants.USER_AGENT_TYPE_HTML)){
			path = PREFIX_HTML;
		}
		if(uat.equals(Constants.USER_AGENT_TYPE_WML)){
			path = PREFIX_WML;
		}
		path = path + sightid + HOME_PATH;
		return path;
	}
}
